<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import { io } from 'socket.io-client'
import type { Socket } from 'socket.io-client'
import { nextTick, onMounted, onUnmounted, provide, ref } from 'vue'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import { MsgType, OrderType } from '@/enums'
import type { TimeMessages, Message } from '@/types/room'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { getOrderDetail } from '@/services/consult'
import { showToast } from 'vant'
const route = useRoute()
const store = useUserStore()
let socket: Socket
// 聊天列表
const list = ref<Message[]>([])

onMounted(() => {
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })
  // 监听建立连接
  socket.on('connect', () => {
    console.log('建立连接成功...')
  })
  // 监听错误信息
  socket.on('error', () => {
    console.log('错误信息....')
  })
  // 监听关闭连接
  socket.on('disconnect', () => {
    console.log('关闭连接')
  })
  // 监听默认聊天记录
  socket.on('chatMsgList', async ({ data }: { data: TimeMessages[] }) => {
    // 处理数据列表
    // 生成一个新的列表 - 新增了一项 - 通知时间
    const arr: Message[] = []
    data.forEach((item, index) => {
      if (index === 0) time.value = item.createTime
      arr.push({
        id: item.createTime,
        msgType: MsgType.Notify,
        createTime: item.createTime,
        msg: {
          content: item.createTime
        }
      })
      item.items.forEach((v) => {
        // 是否可以滚动
        // 什么情况下可以滚动 - initialMsg 值为true 的情况下 (首次加载)
        // 首次加载的时候 - 20条数据 isScroll = true / 下拉 isScroll = false
        v.isScroll = initialMsg.value === true
      })
      arr.push(...item.items)
    })
    // 追加到聊天列表中
    console.log(data)
    list.value.unshift(...arr)
    loading.value = false
    if (!data.length) return showToast('没有聊天记录了')
    await nextTick()
    // 首次初始化消息列表 - 滚动到底部
    // 下拉加载 - 不滚动到底部
    if (initialMsg.value) {
      initialMsg.value = false
      // 最后一条消息的id - 设置为已读
      socket.emit('updateMsgStatus', arr[arr.length - 1].id)
      window.scrollTo(0, document.body.scrollHeight)
    }
  })
  // 监听订单状态变化
  socket.on('statusChange', async () => {
    // 重新更新订单信息
    const res = await getOrderDetail(route.query.orderId as string)
    consult.value = res.data
    console.log('有医生接单了', res.data.status)
  })
  // 监听自己/医生发送的消息
  socket.on('receiveChatMsg', async (event: Message) => {
    console.log(event)
    // 将消息设置为已读
    socket.emit('updateMsgStatus', event.id)
    list.value.push(event)
    await nextTick()
    //滚动页面
    window.scrollTo(0, document.body.scrollHeight)
  })
})
onUnmounted(() => {
  // 关闭连接
  socket.close()
})

// 订单信息
const consult = ref<ConsultOrderItem>()
onMounted(async () => {
  const res = await getOrderDetail(route.query.orderId as string)
  console.log(res.data)
  consult.value = res.data
})

// 发送文字消息
const sendText = (text: string) => {
  console.log('获取的文字内容', text)
  socket.emit('sendChatMsg', {
    from: store.user?.id, // 发送人
    to: consult.value?.docInfo?.id, // 接收人
    msgType: MsgType.MsgText, // 消息类型
    msg: {
      // 消息内容
      content: text
    }
  })
}
// 发送图片消息
const sendImage = (picture: Image) => {
  console.log(picture)
  socket.emit('sendChatMsg', {
    from: store.user?.id, // 发送人
    to: consult.value?.docInfo?.id, // 接收人
    msgType: MsgType.MsgImage, // 消息类型
    msg: {
      // 消息内容
      picture
    }
  })
}
// 下拉加载
const loading = ref(false)
// 起始时间
const time = ref('')
// 初始化消息 - 首次加载
const initialMsg = ref(true)
const onRefresh = () => {
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
  // loading.value = false
}
// 提供订单信息
provide('consult', consult)
// 提供修改信息的方法
const completeEvaDoc = (score: number) => {
  // 未评价的对象
  const item = list.value.find((v) => v.msgType === MsgType.CardEvaForm)
  if (item) {
    // 将分数添加到该对象中 - 为了接下来的渲染
    item.msg.evaluateDoc = { score }
    // 将消息状态由未评价改为已评价
    item.msgType = MsgType.CardEva
  }
}
provide('completeEvaDoc', completeEvaDoc)
</script>

<template>
  <div class="room-page">
    <!-- 导航栏 -->
    <cp-nav-bar title="医生问诊室"></cp-nav-bar>
    <!-- 问诊状态 -->
    <room-status
      :status="consult?.status"
      :countdown="consult?.countdown"
    ></room-status>
    <!-- 问诊消息 -->
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message :list="list"></room-message>
    </van-pull-refresh>
    <!-- 操作栏组件 -->
    <!-- 禁用: 订单的状态不处于接诊中 -->
    <room-action
      @send-text="sendText"
      @send-image="sendImage"
      :disabled="consult?.status !== OrderType.ConsultChat"
    ></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
